package org.huzhp.security.wx;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @Description 微信登陆鉴权 Provider，要求实现 AuthenticationProvider 接口
 * @Author huzp
 * @Data 2019/3/28
 * @Version 1.0
 */
public class WxAuthenticationProvider implements AuthenticationProvider {
    private WxUserDetailService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WxAuthenticationToken authenticationToken = (WxAuthenticationToken) authentication;

        String code = (String) authenticationToken.getPrincipal();

        UserDetails userDetails = null;

        // 此时鉴权成功后，应当重新 new 一个拥有鉴权的 authenticationResult 返回
        WxAuthenticationToken authenticationResult = new WxAuthenticationToken(userDetails, authenticationToken.getState(), userDetails.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 判断 authentication 是不是 WxAuthenticationToken 的子类或子接口
        return WxAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(WxUserDetailService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
